<?php
// Conflict manage
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

class ConflictController extends BaseController {
	// conflict list
	public function index(){
		$wheres_A = $wheres_B = $data = $dlist =  array();
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$psize = I('get.psize', $this->m_psize,'intval');
		// $p = I('get.p','','intval');

		$customer_name = I('get.customer_name','','trim');
		$conflict_person = I('get.conflict_person','','trim');	
		$dealstatus = I('get.dealstatus',0,'intval');
		// $create_time = 	I('get.recordStartTime');
		// $end_time = I('get.recordEndTime');
		$search_userManager = I('get.search_userManager',0,'intval');
		
		if ($customer_name) {
				$map = array();	
				if(strlen($customer_name) > 3 && is_numeric($customer_name))$map['customer.phone'] = array('like',"%".$customer_name."%");
				$map['customer.nickname'] = array('like',"%".$customer_name."%");
				$map['customer.customer_code'] = array('like',"%".$customer_name."%");
				$map['_logic'] = 'or';
				$wheres['_complex'] = $map;
			}
		if ($conflict_person) {
				$wheres['c.nickname'] = array('like',"%".$conflict_person."%");
			}
		if($search_userManager){
			$map['pay_record.sales_manager'] = $search_userManager;
			$map['sector.manager_id'] = $search_userManager;
			$map['_logic'] = 'or';
			$wheres['_complex'] = $map;
		}
		// if ($create_time && $end_time) {
		// 		$tm_s = strtotime( $create_time );
		// 		$tm_e = strtotime( $end_time );
		// 		if($tm_e < $tm_s) break;
		// 		else{
		// 			$stime = date('Y-m-d 00:00:00', $tm_s );
		// 			$etime =  date('Y-m-d 23:59:59', $tm_e );
		// 			$wheres['conflict.create_time'] = array('between', array($stime, $etime ));					
		// 		}
		// 	}
		// if ($owncompany) {
		// 		$wheres['conflict.claim_user_subcompany'] = array('eq',$owncompany);	
		// 	}
		if($dealstatus){
				$wheres['conflict.status'] = array('eq',$dealstatus);
			}	

		$wheres['_string'] = "1=1";
		$wheres['conflict.is_delete'] = array('neq',1);
		$wheres['pay_record.record_status'] = array('eq',1);
		if( !$psize )
			$psize = $this->m_psize;
		else if( $psize > 20 )
			$psize = $this->m_psize;
		$cnt = D('Admin/Conflict')->field('conflict.create_time,conflict.claim_user_id_id,customer.nickname,customer.customer_id,pay_record.pay_mount,pay_record.pay_time,a.nickname as username,b.nickname as respondent_manager,conflict.status,conflict.conflict_id')
							->join('LEFT JOIN conflict_pay ON conflict_pay.conflict_id = conflict.conflict_id')
							->join('LEFT JOIN pay_record ON conflict_pay.pay_id = pay_record.pay_id')
							->join('JOIN customer ON customer.customer_id = conflict.customer_id')
							->join('LEFT JOIN user as a  ON a.user_id = pay_record.sales_person')
							->join('LEFT JOIN user as b  ON b.user_id = pay_record.sales_manager')
							// ->join('LEFT JOIN sector ON pay_record.sales_sector = sector.sector_id')
							->join('LEFT JOIN user as c ON c.user_id = conflict.claim_user_id_id')
							->join('LEFT JOIN sector ON sector.sector_id = c.sector_id')
							->join('LEFT JOIN user as d ON d.user_id = sector.manager_id')
							->order('conflict.create_time desc')
							->where($wheres)
							->count();
		$Page = new \Common\ORG\Page( $cnt, $psize );
		$resconflict = D('Admin/Conflict')->field('conflict.create_time,c.nickname as claimant,d.nickname as claimant_manager,customer.nickname,customer.customer_id,pay_record.pay_mount,pay_record.pay_time,a.nickname as username,b.nickname as respondent_manager,conflict.status,conflict.conflict_id')
							->join('LEFT JOIN conflict_pay ON conflict_pay.conflict_id = conflict.conflict_id')
							->join('LEFT JOIN pay_record ON conflict_pay.pay_id = pay_record.pay_id')
							->join('JOIN customer ON customer.customer_id = conflict.customer_id')
							->join('LEFT JOIN user as a  ON a.user_id = pay_record.sales_person')
							->join('LEFT JOIN user as b  ON b.user_id = pay_record.sales_manager')
							// ->join('LEFT JOIN sector ON pay_record.sales_sector = sector.sector_id')
							->join('LEFT JOIN user as c ON c.user_id = conflict.claim_user_id_id')
							->join('LEFT JOIN sector ON sector.sector_id = c.sector_id')
							->join('LEFT JOIN user as d ON d.user_id = sector.manager_id')
							->order('conflict.create_time desc')
							->limit($Page->firstRow.','.$Page->listRows )
							->where($wheres)
							->select();
		// foreach($resconflict as $key => $val){
		// 	$claimant 						= M('user')
		// 												->field('user.nickname,sector.manager_id')
		// 												->join ('LEFT JOIN sector ON sector.sector_id = user.sector_id')
		// 												->where(array('user.user_id'=>$val['claim_user_id_id']))
		// 												->find();
		// 	$claimant_manager 				= M('user')
		// 												->field('nickname')
		// 												->where(array('user_id'=>$claimant['manager_id']))
		// 												->find();
		// 	$resconflict[$key]['claimant'] = $claimant['nickname'];
		// 	$resconflict[$key]['claimant_manager'] = $claimant_manager['nickname'];
		// }
		if ($resconflict) {
			$res['data'] = $resconflict;
			$res['rcode'] = 1;
			$res['pall'] = $Page->getTotalPages();
			$res['p'] = $Page->nowPage;
			$res['psize'] = $psize;
			$res['sql'] = D('Admin/Conflict')->getlastsql();
		}
		e_json($res);
	}

	//get Customer Message
	public function GetMsg(){
		$res = array();
		//$CusMsg = M('Customer')->field('customer_id,nickname,phone')->select();
		$CusMsg = false;
		if ($CusMsg) {
			$res['rcode'] = 1;
			$res['data'] = $CusMsg;
		}else
			$res['sql'] = M('Customer')->getLastSql();
 		e_json($res);
	}

	// get User Message
	public function GetUserMsg(){
		$res = array();
		//$UserMsg = M('User')->field('user_id,nickname,phone')->select();
		$UserMsg = false;
		if ($UserMsg) {
			$res['rcode'] = 1;
			$res['data'] = $UserMsg;
		}else
			$res['sql'] = M('User')->getLastSql();
 		e_json($res);		
	}

	// get Customer Payment Records
	public function CustomerPayRecords(){
		$res = array('rcode'=>0,'data'=>'');
		$customer_id = I('post.CustomerId',0,'intval');
		$CstPayReds = M('Pay_record')
									->field('pay_record.pay_id,customer.nickname as customer_name,user.nickname as usernickname,sector.sector_name,pay_record.pay_time,pay_record.pay_way,pay_record.pay_mount,user.user_id,pay_record.is_conflict')
									// if customer doesn't exist ,you can't search customer you need
									->join('LEFT JOIN customer ON pay_record.customer_id = customer.customer_id')
									->join('LEFT JOIN user ON pay_record.sales_person = user.user_id')
									->join('LEFT JOIN sector ON pay_record.sales_sector = sector.sector_id')
									->where(array('pay_record.customer_id'=>$customer_id,'pay_record.record_status'=>1,'pay_record.audit_res'=>1))
									->order('pay_record.pay_time desc')
									->limit(5)
									->select();
	   $conflictPayRecords = M('conflict_pay')->field('pay_id')->where(array('is_delete'=>array('neq',1)))->select();
	   foreach($conflictPayRecords as &$value){
			$conflictPayRecords_PayId[] = $value['pay_id'];
	   }
		foreach($CstPayReds as $k => $v ){
			if(!in_array($v['pay_id'],$conflictPayRecords_PayId)){
				$mergeConflictPayrecords[$k] = $v;
			}
		}
		if ($mergeConflictPayrecords) {
 			$res['rcode'] = 1;
 			$res['data'] = $mergeConflictPayrecords;
		}else{
			$res['date'] ='没有匹配到合适的付款记录';
		}
		e_json($res);
	}

	// add conflictg Message
	public function add(){
		$res = array('rcode'=>0,'data'=>'','msg'=>'');
		$customer_id = I('post.customer_id',0,'intval');
		$user_id = I('post.user_id',0,'intval');
		$checkboxMsg = $_POST['checkboxMsg'];
		$radioMsg = I('post.radioMsg',0,'intval');
		$dropdownMsg =I('post.dropdownMsg',0,'intval');
		$payamount = $_POST['payamount'];
		$textarea = I('post.textarea','','trim');
		$dropdownUser = I('post.dropdownUser',0,'trim');
		$customer_sales = I('post.customerSales',0,'intval');
		$note = I('post.note','','trim');
		$addMsgBack = D('Conflict')->addMsg(array('customer_id'=>$customer_id,'user_id'=>$user_id,'checkboxMsg'=>$checkboxMsg,'radioMsg'=>$radioMsg,'dropdownMsg'=>$dropdownMsg,'textarea'=>$textarea,'note'=>$note,'payamount'=>$payamount,'dropdownUser'=>$dropdownUser,'customersales'=>$customer_sales));		
		if($addMsgBack){
			$res['rcode'] = 1;
			$res['msg'] = '添加申诉记录成功';
		}else{
			$res['msg'] = '添加申诉记录失败';
		}
		e_json($res);
	}


	//edit conflict Message 
	public function editConflictMsg(){
		$res = array('rcode'=>0,'data'=>'','msg'=>'' );
		if(IS_GET){
			$conflict_id =  I('get.conflict_id','false', 'trim');
			$customer_id= I('get.customer_id','false','trim');
			$wheres = array();
			if( $conflict_id ){
				$wheres['conflict.conflict_id'] = array('eq', $conflict_id );
				$data_partone = D('Conflict')->field('customer.nickname,user.nickname as username,conflict.remark,conflict.notify,conflict.customer_belong,conflict.status,conflict.customer_id,conflict.customer_belong,conflict.claim_user_id_id')
												->join('JOIN customer ON customer.customer_id = conflict.customer_id')
												->join('LEFT JOIN user ON user.user_id = conflict.claim_user_id_id')
												->where( $wheres )
												->find();
				$data_parttwo = M('pay_record')
												->field('pay_record.pay_id,customer.nickname as customer_name,user.nickname as usernickname,sector.sector_name,pay_record.pay_time,pay_record.pay_way,pay_record.is_conflict,pay_record.pay_mount,user.user_id')
												->join('JOIN customer ON pay_record.customer_id = customer.customer_id')
												->join('LEFT JOIN user ON pay_record.sales_person = user.user_id')
												->join('LEFT JOIN sector ON pay_record.sales_sector = sector.sector_id')
												->where(array('pay_record.customer_id'=>$customer_id,'pay_record.record_status'=>1,'pay_record.audit_res'=>1))
												->order('pay_record.pay_time desc')
												// ->limit(5)
												->select();
				// $res['count'] = count($data_parttwo);
				$res['data_partthree'] = D('Conflict')
												->field('conflict_pay.pay_id')
												->join('LEFT JOIN conflict_pay ON conflict_pay.conflict_id = conflict.conflict_id')
												->where(array('conflict.conflict_id'=>$conflict_id))
												->select();
				$data_partfour= M('customer')->field('customer.sales_person,user.nickname')
											->join('user ON user.user_id = customer.sales_person')
											->where(array('customer.customer_id'=>$customer_id))->find();
				$res['data_partfour'] = $data_partfour['nickname'];

				for ($i=0; $i <count($data_parttwo); $i++) { 
						$conflictdata[] = $data_partone + $data_parttwo[$i];
				}

				// judge which record is signed ,if it is signed , add field named verify
				foreach ($conflictdata as $k => $val) {
					foreach ($res['data_partthree'] as &$vals) {
						if($vals['pay_id'] == $val['pay_id']){
							$conflictdata[$k]['verify'] = 1;
						}
					}
				}
				foreach($conflictdata as &$value){
					if($value['verify'] == 1){
						$conflictdata_res[] = $value;
					}
				}
			}
			else
				$res['msg'] = L("PARAM_WRONG");
			if( !$conflictdata ){
				$res['msg'] = L('NO_DATA');
			}else{
				$res['rcode'] = 1;
				$res['msg'] = 'ok';
				$res['data'] = $conflictdata_res;
			}				
		}
	    e_json($res);
	}

	// delete conflict records
	// public function conflictdel(){
	// 	$res = array('code' => 0, 'data'=>'','msg'=>'');
	// 	$conflict_del = I('post.conflict_id',0,'intval');
	// 	$del_res = D('Conflict')->delconflictrecord(array('conflict_id'=>$conflict_del));
	// 	if ($del_res['code'] == 1) {
	// 			$res['code'] = 1;
	// 			$res['msg'] = '删除成功';
	// 	}
	// 	e_json($res);
	// }

	// get subcompany
	// public function getSector()
	// {
	// 	$res = list_to_company();
	// 	echo json_encode( array("psector"=>array_values($res)));
	// 	exit();	
	// }

	// get getCustomerServicePeople
	// public function getCustomerServicePeople(){
	// 	$customerMsg= I('post.customerMsg');
	// 	$payres = M('pay_record')
	// 						->distinct(true)
	// 						->field('user.user_id,user.nickname')
	// 						->join('user ON user.user_id = pay_record.sales_person')
	// 						->where(array('pay_record.payrecord_id'=>array('IN',$customerMsg)))
	// 						->select();
	// 	for ($i=0; $i < count($payres) ; $i++,$j++) { 
	// 			$merge[$i]['user_id'] = $payres[$i]['user_id'];
	// 			$merge[$i]['nickname'] = $payres[$i]['nickname'];
	// 	}
	// 	e_json($merge);
	// }


	// get getCustomerServicePeople
	public function getCustomerServicePeople(){
		$customerMsg= I('post.customerMsg');
		$user_id = I('post.UserID',false,'intval');
		$payres = M('pay_record')
							->distinct(true)
							->field('user.user_id,user.nickname')
							->join('user ON user.user_id = pay_record.sales_person')
							->where(array('pay_record.pay_id'=>array('IN',$customerMsg),'pay_record.record_status'=>1))
							->select();
		if($user_id){
			$userMessage = M('user')->field('user_id,nickname')->where(array('user_id'=>$user_id))->find();
			for ($i=0; $i < count($payres) ; $i++) { 
					if($i == 0){
						$merge[$i]['user_id'] = $userMessage['user_id'];
						$merge[$i]['nickname'] = $userMessage['nickname'];
					}
					$merge[$i+1]['user_id'] = $payres[$i]['user_id'];
					$merge[$i+1]['nickname'] = $payres[$i]['nickname'];
			}
		}else{
			for ($i=0; $i < count($payres) ; $i++,$j++) { 
					$merge[$i]['user_id'] = $payres[$i]['user_id'];
					$merge[$i]['nickname'] = $payres[$i]['nickname'];
			}			
		}
		e_json($merge);
	}


	// get customer name 
	public function getcustomername(){
		//	WJW 20170725 自动补全修改
		$res = array('rcode'=>0,'CustomerMsg'=>'','msg'=>'' );
		$where = array();
		$parame = I('get.parame');
		if($parame){
			if (preg_match('#^\d{4,13}$#', $parame )) {
                $where['phone'] = array('like','%'.$parame.'%');   
            }
            else {
            	$where['nickname'] = array('like','%'.$parame.'%');
            }	
		}	
		
		$customer = M('customer')->field('nickname,customer_id')->where($where)->select();
		if($customer)
		{
			$res['rcode'] = 1;
			$res['CustomerMsg'] = $customer;
		}
		e_json($res);
	}

	// get user name 
	public function getusername(){
		$res = array('rcode'=>0,'CustomerMsg'=>'','msg'=>'' );
		//	WJW 20170725 自动补全修改
		$where = array();
		$parame = I('get.parame');
		if($parame){
			if (preg_match('#^\d{4,13}$#', $parame )) {
                $where['phone'] = array('like','%'.$parame.'%');   
            }
            else {
            	$where['nickname'] = array('like','%'.$parame.'%');
            }	
		}	
		
		$user = M('user')->field('nickname,user_id')->where($where)->select();
		if($user)
		{
			$res['rcode'] = 1;
			$res['getUser'] = $user;
		}
		
		e_json($res);
	}

	// get userManager name
    public function GetUserManagerMsg(){
		$res = array('rcode'=>0,'data'=>'','msg'=>'ok');
		$UserManagerMsg = M('sector')->distinct(true)
							->field('user.user_id,user.nickname')
							->join('user ON sector.manager_id = user.user_id')
							->select();
		if ($UserManagerMsg) {
			$res['rcode'] = 1;
			$res['data'] = $UserManagerMsg;
		}else
			$res['sql'] = M('User')->getLastSql();
 		e_json($res);	
	}

	// get userManagerrecord name
	public function getusermanagername(){
		$userManagerId = I('post.userManagerId',0,'intval');
		$res = 	M('user')->field('nickname,user_id')->where(array('user_id'=>$userManagerId))->find();
		e_json($res);		
	}

	// get the person of servicing getcustomer
	public function customerbelong(){
		$res = array('rcode'=>0,'data'=>'','msg'=>'' );
		$customer_id = I('customer_id','','intval');
		$username = M('user')
								->field('user.nickname')
								->join('LEFT JOIN customer ON customer.sales_person = user.user_id')
								->where(array('customer.customer_id'=>$customer_id))
								->find();
		if($username){
			$res['rcode'] = 1;
			$res['data'] = $username['nickname'];
			$res['msg'] = 'ok';
		}
		e_json($res);
	}
	// export conflictRecords
	// public function exportRecords(){
	// 	$wheres = $res = array();
	// 	$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
	// 	$GET = $_GET;
    //     if($GET['customer_name'])                                      $wheres['customer.nickname'] = array('like',"%".$GET['customer_name']."%");
    //     if($GET['conflict_person'])                                    $wheres['user.nickname'] =array('like',"%".$GET['conflict_person']."%");
    //     if($GET['recordStartTime'] && $GET['recordEndTime'])           $wheres['conflict.create_time'] = array('between',array($GET['recordStartTime'],$GET['recordEndTime']));
    //     if ($GET['company_opinion']) 							       $wheres['conflict.claim_user_subcompany'] =  array('eq',$GET['company_opinion']);
	// 	if($GET['dealstatus'])                                         $wheres['conflict.status'] = array('eq',$GET['dealstatus']);
	// 																   $wheres['_string'] = '1=1';
	// 																   $wheres['conflict.is_delete'] = array('neq',1);

	// 	// reference
	// 	import("Common.ORG.Excel");
	// 	$SExcel = new \Common\ORG\Excel();
	// 	$SSheet = new \Common\ORG\Sheet("撞单数据");

	// 	$resconflict = D('Admin/Conflict')->field('conflict.create_time,conflict.claim_user_subcompany,conflict.claim_user_id_id,conflict.notify,customer.nickname,pay_record.pay_mount,pay_record.pay_time,a.nickname as username,b.nickname as respondent_manager,sector.sector_name,conflict.status')
	// 						->join('LEFT JOIN conflict_pay ON conflict_pay.conflict_id = conflict.conflict_id')
	// 						->join('LEFT JOIN pay_record ON conflict_pay.pay_id = pay_record.payrecord_id')
	// 						->join('JOIN customer ON customer.customer_id = conflict.customer_id')
	// 						->join('LEFT JOIN user as a  ON a.user_id = pay_record.sales_person')
	// 						->join('LEFT JOIN user as b  ON b.user_id = pay_record.sales_manager')
	// 						->join('LEFT JOIN sector ON pay_record.sales_sector = sector.sector_id')
	// 						->order('conflict.create_time desc')
	// 						->where($wheres)
	// 						->select();
	// 	// set table header content 
	// 	$column = array('争议提起时间','进款时间','客户','金额','撞单业务','撞单经理','撞单团队','提争议业务','提争议经理','提争议团队','判定结果');
	// 	$SSheet->setColumn( $column );		
	// 	foreach($resconflict as $key => $val){
	// 		// $respondent_manager    						= M('sector') 
	// 		// 												->field('user.nickname')
	// 		// 												->join('LEFT JOIN user ON sector.sector_id = user.sector_id')
	// 		// 												->where(array('sector.manager_id'=>$val['manager_id']))
	// 		// 												->find();
	// 		// $resconflict[$key]['respondent_manager']    = $respondent_manager['nickname'];
	// 		$claimant 									= M('user')
	// 		 												->field('user.nickname,sector.manager_id')
	// 														->join ('LEFT JOIN sector ON sector.sector_id = user.sector_id')
	// 														->where(array('user.user_id'=>$val['claim_user_id_id']))
	// 													    ->find();
	// 		$claimant_manager 							= M('user')
	// 														->field('nickname')
	// 														->where(array('user_id'=>$claimant['manager_id']))
	// 														->find();
	// 		$sector_name 								= M('conflict')
	// 														->field('sector.sector_name')
	// 														->join('sector ON sector.sector_id = conflict.claim_user_subcompany')
	// 														->where(array('claim_user_subcompany'=>$val['claim_user_subcompany']))
	// 														->find();
	// 		$resconflict[$key]['claimant'] = $claimant['nickname'];
	// 		$resconflict[$key]['claimant_manager'] = $claimant_manager['nickname'];
	// 		$resconflict[$key]['claim_user_subcompany'] = $sector_name['sector_name'];
	// 		// switch ($val['status']) {
	// 		// 	case '1':
	// 		// 		$resconflict[$key]['result'] = '此单业绩归'.$val['sector_name'].'所有';
	// 		// 		break;
	// 		// 	case '2':
	// 		// 		$resconflict[$key]['result'] = '此单业绩评分，归'.$val['sector_name'].'和'.$res[$key]['claim_user_subcompany'].'共同所有';
	// 		// 		break;
	// 		// 	case '3':
	// 		// 		$resconflict[$key]['result'] = '此单业绩归'.$res[$key]['claim_user_subcompany'].'所有';
	// 		// 		break;
	// 		// 	case '4':
	// 		// 		$resconflict[$key]['result'] = '客户退款,业绩不属于任何团队';
	// 		// 		break;
	// 		// }

	// 	}
	// 	if( $resconflict ){
	// 		foreach($resconflict as $vd ){
	// 			$row = array();
	// 			$row[] = $vd['create_time'];
	// 			$row[] = $vd['pay_time'];
	// 			$row[] = $vd['nickname'];
	// 			$row[] = $vd['pay_mount'];
	// 			$row[] = $vd['username'];
	// 			$row[] = $vd['respondent_manager'];
	// 			$row[] = $vd['sector_name'];
	// 			$row[] = $vd['claimant'];
	// 			$row[] = $vd['claimant_manager'];
	// 			$row[] = $vd['claim_user_subcompany'];
	// 			$row[] = $vd['notify'];
 	// 			$SSheet->addRow( $row );
	// 		}
	// 	}
	// 	$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("撞单数据导出");
	// 	if( $exportData['rcode'] ){
	// 		$exportData['name'] = basename( $exportData['data']['view_path'] );
	// 		$exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
	// 		echo $exportData['excel'];
	// 		exit();
	// 	}
	// }
}
?>   